document.write("<script language=javascript src='../js/validate.js'></script>");
var app=angular.module('Login',['ngRoute'])
            app.config(['$routeProvider', function($routeProvider){
               	$routeProvider.when('/login', {
					templateUrl: 'login.html',
					controller: 'loginCtrl'
				});
            }]);
            app.controller("loginCtrl", function($scope,$location,$http,$window) {
            	$scope.removeE = function(){
            		$(".has-feedback").removeClass("has-error")
            	}
            	$('#usernameInput').focus()
            	//跳往系统登录页
            	$scope.jumpToLogin = function(){
            			window.location.href= 'login.html';
            	}
            	console.log(resultPath);
            	$scope.getJson = function(resultPath,data,method,successfn){
            			$http({
            	                method: method, 
            	                dataType:"json",
            	                url: resultPath,
            	                data:data,
            	                headers: {
            	                	'Content-Type': 'application/json',
            	                	'token_id':'11'
	         	                }
 						
            	            }).
            	            success(function(data) {
								successfn(data);
            	            }).
            	            error(function(data, status) {
//          	               console.log(data.msg);
            	            });
            		
            	}
            	$scope.getJso = function(resultPath,data,method,token,successfn){
            			$http({
            	                method: method, 
            	                dataType:"json",
            	                url: resultPath,
            	                data:data,
            	                headers: {
            	                	'Content-Type': 'application/json',
            	                	'token_id':token
	         	                }
 						
            	            }).
            	            success(function(data) {
								successfn(data);
            	            }).
            	            error(function(data, status) {
//          	               console.log(data.msg);
            	            });
            		
            	}
            	$scope.user = {}
            	$scope.login = function(){
            		if($scope.user.user_name == undefined || $scope.user.password == undefined){
            			return
            		}else{
            			$scope.getJson(resultPath+'/wisdomeatery/v1/tenants/login',$scope.user,'post',function(data){
            				console.log(data)
            				if(data.code == 0){
            					var storage=window.localStorage;
            					storage.tenantId = data.data.id;
					            //写入token_id字段
//					            storage["token_id"]=data.data;
					            //设施session时效
//					            storage.setMaxInactiveInterval(1800);  //30min
					            //跳转界面
//					            window.location="/SmartCanteen/WebContent/html/authorityControl.html";
								window.location.href = 'authorityControl.html';
					        }else{
            					$('#errorStr').html(data.msg)
								$('#ErrorUser').fadeIn('slow')
								setTimeout("$('.alert').fadeOut('slow')", 3000);
								$(".has-feedback").addClass("has-error")
            				}
            			})
            		}
            	}
            	
            });


//权限控制
			var app1=angular.module('authority',['ngRoute'])
            app1.config(['$routeProvider', function($routeProvider){
		               	$routeProvider.when('/authorityControl', {
										templateUrl: 'authorityControl.html',
										controller: 'authorityCtrl'
							});
            }]);
            
				app1.controller("authorityCtrl", function($scope,$location,$http,$window) {
							$(".modal-dialog").draggable();//为模态对话框添加拖拽
       				 $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
							var storage=window.localStorage;
							$scope.tenantId = storage.tenantId ;
//							$scope.tenantId =  '7157cdb71a934ddd83791f4ca6809af5';
							console.log($scope.tenantId);
							
            	$scope.getJson = function(resultPath,data,method,successfn){
            			$http({
            	                method: method, 
            	                dataType:"json",
            	                url: resultPath,
            	                data:data,
            	                headers: {
            	                	'Content-Type': 'application/json',
            	                	'token_id':'11'
	         	                }
            	            }).
            	            success(function(data) {
														successfn(data);
            	            }).
            	            error(function(data, status) {
//          	               console.log(data.msg);
            	            });
            	}
            	$scope.datas = [];
            	//获取当前企业下所有权限
							$scope.getAuthorities = function(){
								console.log($scope.tenantId);
										$scope.getJson(resultPath+"/wisdomeatery/v1/tenants/"+$scope.tenantId+"/authority",'',"get",function(data){
												console.log(data)
												$scope.datas = data.data ;
										})
							}
							$scope.getAuthorities();
							//退出
							$scope.Exit = function(){
								window.location.href = 'tenantLogin.html';
							}
							//展开缩放树结构模板
							$scope.modalDiv = function(id){
									console.log(id);
									console.log( $('.repeatDiv_'+id).css('display') );
									$('.repeatDiv_'+id).slideToggle("slow");
//									if( $('.repeatDiv_'+id).css('display') == 'block'){
//											$('.repeatDiv_'+id).slideToggle("slow");
//									}else {
//											$('.repeatDiv_'+id).slideToggle("slow");
//									}
							}
							$scope.roleId = '';
							$scope.roleName = '';
							$scope.enterpriseId = '';
							//与数据库交互成功后右上角提示
            	$scope.showSuccess = function(str){
            		$('#successSave').fadeIn('slow')
            		if(str==''){
            			$('#alertStr').html('操作成功')
            		}else{
            			$('#alertStr').html(str)
            		}
            		setTimeout("$('#successSave').fadeOut('slow')",3000);
            	}
            	//与数据库交互失败后右上角提示 str 为要写入的提示文字
            	$scope.showError = function(str){
            		$('#errorSave').fadeIn('slow')
            		if(str==''){
            			$('#errorStr').html('操作失败')
            		}else{
            			$('#errorStr').html(str)
            		}
            		setTimeout("$('#errorSave').fadeOut('slow')",3000);
            	}
            		//企业改变
            		$scope.changeEnter = function(){
            			console.log($scope.enterId);
            			$scope.getRoles();
            			$scope.getAuthorities();
            		}
            		//获取角色(某租户，某企业下的所有角色)
            		$scope.getRoles = function(){
            				$scope.getJson(resultPath+'/wisdomeatery/v1/tenants/'+$scope.tenantId+'/enterprise/'+$scope.enterId+'/get_rolesByEnterprise',{},'POST',function(data){
												console.log(data);
												$scope.roles = data.data;
												$scope.roleId = '';
										})
            		}
							//企业信息获取
							$scope.enterprises=[];
							$scope.enterId = '';
//							$scope.getJson($scope.resultPath+"/wisdomeatery/v1/base_system/enterprise",'',"get",function(data){
								$scope.getJson(resultPath+"/wisdomeatery/v1/tenants/"+$scope.tenantId+"/enterprise",'',"get",function(data){//因为后台登录user信息，暂时写死为战车集团的tenantId,暂时使用此接口调取用户下的企业信息
									console.log(data)
									$scope.enterprises = data.data
									$scope.enterId = $scope.enterprises[0].id ;
									$scope.getRoles();
							})
							//新增角色名称时，
	            $scope.judgeShow = function(){
	            	console.log($scope.roleName);
	            	if( $scope.roleAddName == '' || $scope.roleAddName == undefined){
	            		 $scope.showIt = true;
	            	}else{
	            		$scope.showIt = false;
	            	}
	            }
	            //修改角色名称时，
	            $scope.judgeShow1 = function(){
	            	console.log($scope.roleName);
	            	if( $scope.roleUpdateName == '' || $scope.roleUpdateName == undefined){
	            		 $scope.showUpdate = true;
	            	}else{
	            		$scope.showUpdate = false;
	            	}
	            }
							//打开新增角色模板
							$scope.openRolemodal = function(){
								$scope.roleAddName = '';
									$("#addRole").modal('toggle')
							}
							//确定新增角色
							$scope.addRole_true = function(){
								
									if( isNull($scope.roleAddName) == true){
										$scope.showIt = true;
										return;
									}
									var postData = {
											'name':$scope.roleAddName
									}
									$scope.getJson(resultPath+'/wisdomeatery/v1/tenants/'+$scope.tenantId+'/enterprise/'+$scope.enterId+'/role',postData,'POST',function(data){
												console.log(data);
												if(data.code == 0){
														$scope.showSuccess('操作成功');
														$scope.roles = data.data;
														$("#addRole").modal('toggle');
														//获取角色(某租户，某企业下)
						            		$scope.getRoles();
														
												}else{
														$scope.showError(data.msg);
												}
												
										})
							}
							//打开修改角色模板
							$scope.openUpdateRole = function(){
								console.log($scope.roleId);
								if( $scope.roleId == ''){
									$scope.showError('请选择角色');
									return;
								}
								$scope.roleUpdateName = $scope.roleName ;
								$("#updateRole").modal('toggle');
							}
							//修改角色模板确定键
							$scope.updateRole_true = function(){
								console.log($scope.roleId);
									if( isNull($scope.roleUpdateName) == true){
										$scope.showIt = true;
										return;
									}
									var postData = {
											'name':$scope.roleUpdateName
									}
									$scope.getJson(resultPath+'/wisdomeatery/v1/tenants/'+$scope.tenantId+'/enterprise/'+$scope.enterId+'/role/'+$scope.roleId,postData,'PUT',function(data){
												console.log(data);
												if(data.code == 0){
													$scope.roleId = '';
													$scope.roleUpdateName = '';
													$scope.showSuccess('操作成功');
													$("#updateRole").modal('toggle');
														//获取角色(某租户，某企业下)
						            		$scope.getRoles();
														
												}else{
														$scope.showError(data.msg);
												}
												
										})
							}
							//删除角色
							$scope.delRole = function(){
								console.log($scope.roleId);
								if( $scope.roleId == ''){
									$scope.showError('请选择角色');
									return;
								}
								$("#delRole").modal('toggle');
							}
							//删除角色模板的确定键
							$scope.del_Role = function( roleId){
									$scope.getJson(resultPath+'/wisdomeatery/v1/tenants/'+$scope.tenantId+'/enterprise/'+$scope.enterId+'/role/'+$scope.roleId,'','DELETE',function(data){
													console.log(data);
													if(data.code == 0){
														$scope.roleId = '';
														$scope.showSuccess('操作成功');
														$("#delRole").modal('toggle');
															//获取角色(某租户，某企业下)
							            		$scope.getRoles();
													}else{
															$scope.showError(data.msg);
													}
											})
							}
							
							//点击某个角色，获取权限
							$scope.getAuthority = function(event,roleId,roleName,enterpriseId){
									event.stopPropagation();
									$scope.roleId = roleId ;
									$scope.roleName = roleName ;
									$scope.enterpriseId = enterpriseId;
									console.log($scope.roleId);
									console.log($scope.roleName);
									console.log($scope.enterpriseId);
									console.log($scope.tenantId);
									var target = event.target ;
									$(target).siblings().each(function(){
					   					$(this).css('background-color','#ffffff');
					   			});
						   		$(target).css('background-color','#e4eaec');
//						   		var postData = {
//						   						'':''
//						   		};
									//查询此角色拥有权限
									$scope.getJson(resultPath+"/wisdomeatery/v1/tenants/"+$scope.tenantId+"/enterprise/"+$scope.enterpriseId+"/role/"+$scope.roleId+"/getAuthorityByTidAndRid",'',"get",function(data){
												console.log(data)
												$scope.datas = data.data ;
										})
							}
							//保存角色权限
							$scope.saveAuthority = function(){
								console.log($scope.roleId);
									if( $scope.roleId == ''){
										$scope.showError('请选择角色');
										return;
									}
									console.log($scope.datas);
									//保存角色权限
									$scope.getJson(resultPath+"/wisdomeatery/v1/tenants/"+$scope.tenantId+"/enterprise/"+$scope.enterpriseId+"/role/"+$scope.roleId+"/authority",$scope.datas,"PUT",function(data){
												console.log(data);
												if( data.code == 0){
														$scope.showSuccess('操作成功');
														//重新查询此角色拥有权限
														$scope.getJson(resultPath+"/wisdomeatery/v1/tenants/"+$scope.tenantId+"/enterprise/"+$scope.enterpriseId+"/role/"+$scope.roleId+"/getAuthorityByTidAndRid",'',"get",function(data){
																console.log(data)
																$scope.datas = data.data ;
														})
												}
											 
										})
							}
							//判断上下级选择状态
							$scope.judgeState = function(event,id,pid,level){
										event.stopPropagation();
										console.log(id);
										console.log(pid);
										console.log(level);
										var target = event.target;
										var arr = $scope.datas.children;
										console.log(arr);
										var state = $(target).is(':checked');
										if( state ){//将上级或者上上级的状态也设置为true
//												$('#checkbox_'+pid).prop('checked',true);
//												if( pid != 0){
//													$('#checkbox_'+$('#checkbox_'+pid).attr('class').substring(9,13)).prop('checked',true);
//												}
													if( level == 1){
														for( var i = 0 ;i < arr.length ; i++){
															if( arr[i].id ==  id){
																var twoLevelArray = arr[i].children;
																for( var j = 0; j< twoLevelArray.length ; j++ ){
																	twoLevelArray[j].checked = true ;
																}
															}
														}
														return;
													}
													if( level == 2){
														for( var i = 0 ;i < arr.length ; i++){
																if( arr[i].id ==  pid){
																		arr[i].checked = true ;
																}
														}
													}
													if( level == 3 ){
															var ppid = '';
															for( var i = 0 ;i < arr.length ; i++){
																var newChildrenArr = arr[i].children;
																for( var j = 0 ;j < newChildrenArr.length ; j++ ){
																		if( newChildrenArr[j].id ==  pid){
																				newChildrenArr[j].checked = true ;
																				ppid = newChildrenArr[j].parentId ;
																		}
																}
															}
															for( var i = 0 ;i < arr.length ; i++){
																	if( arr[i].id ==  ppid){
																			arr[i].checked = true ;
																	}
															}
													}



										}
										//判断是否可以取消选择
										if( level == 1 ){
												for( var i = 0 ;i < arr.length ; i++){
													var newChildrenArr = arr[i].children;
													for( var j = 0 ;j < newChildrenArr.length ; j++ ){
															if( newChildrenArr[j].parentId ==  id && newChildrenArr[j].checked ){
																	$scope.showError('子分类中有被选项时，无法撤销选择');
																	arr[i].checked = true ;
																	return;
															}
													}
												}
										}
										
										if( level == 2 ){
												var level3Array = [];
												for( var i = 0 ;i < arr.length ; i++){
													var newChildrenArr = arr[i].children;
													for( var j = 0 ;j < newChildrenArr.length ; j++ ){
															if( newChildrenArr[j].id ==  id ){
																	level3Array = newChildrenArr[j].children ;
																	for( var k = 0;k< level3Array.length ; k++){
																			if( level3Array[k].checked ){
																				$scope.showError('子分类中有被选项时，无法撤销选择');
																				 newChildrenArr[j].checked = true ;
																				 return;
																			}
																	}
															}
													}
												}
										}
							}
						            	
            });